package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.common.utils.JwtUtils;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;



    @Override
    public void sendCode(String phone) {
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        Boolean b = redisTemplate.hasKey(key);
        if(b){ //有验证码 防止频繁发送
            //检查手机号是否已经发送了，并且在有效期内！在的话，告诉他发送频繁
            //前端倒计时60秒(2) 60s后可重复发送 验证码有效期为300秒(1)
            //redisTemplate获取剩余时间（3）  1 - 3 > 60可以发送
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            Long expire = redisTemplate.getExpire(key);
            if(appLoginCodeTtlSec - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //1.生成验证码
        //随机生成一个6位验证码
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            Random random = new Random();
            int n = random.nextInt(10);
            sb.append(n);
        }
        String code = sb.toString();
        System.out.println("验证码 = " + code);
        //2.将验证码存储到redis key为手机号
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
        //3.发送 （假发）
        //返回ok

    }

    @Override  //app登录接口
    public String login(LoginVo loginVo) {
        //1.通过key:前缀+手机号去redis取value验证码
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = (String) redisTemplate.opsForValue().get(key);
        //2.没有或者有，对比输入的和存储的不一致 验证码错误
        if(code == null || !code.equals(loginVo.getCode())){
           throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //3.对 检查手机号有无注册
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());//前端传来的手机号与数据库中的phone对比
        UserInfo userInfo = userInfoService.getOne(lambdaQueryWrapper);//有无这个用户
        if(userInfo == null){//4.没注册，先保存
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setAvatarUrl("http://www.baidu.com/img/bd_logo.png");
            //设置佚名 + 手机号后四位
            userInfo.setNickname("佚名"+loginVo.getPhone().substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo);
        }
        //5.用户是否被禁用
        if (userInfo.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //6.没有禁用 创建token token信息包含用户id，phone
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }

    @Override
    public UserInfoVo info(String accessToken) {
        //解析前端token里的userId---前端--请求头 access_token 从中获取userid --通过id返回用户信息
        Claims claims = JwtUtils.parseToken(accessToken);
        Integer userId  = (Integer) claims.get("userId");
        UserInfo userinfo = userInfoService.getById(userId);
        //封装vo
        UserInfoVo userInfoVo = new UserInfoVo(userinfo.getNickname(),userinfo.getAvatarUrl());
        return userInfoVo;
    }
}
